package com.groupbuying.sysconfig.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * class_name: WxCheckController
 * package: com.groupbuying.sysconfig.controller
 * description: 微信支付controller
 * creat_user: Ywxd
 * creat_date: 2019/6/11
 * creat_time: 11:07
 **/
@RestController
@RequestMapping()
public class WxCheckController {

	private static final String token = "KHQuWTW3XqKIMlFx";

	/**
	* Description 微信服务器校验 <br>
	*
	* @author Ywxd <br>
	* @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
	* @param timestamp 时间戳
	* @param nonce 随机数
	* @param echostr 随机字符串
	* @return TODO
	* @createDate 2019/6/11 10:33<br>
	**/
	@GetMapping("/wxcheck")
	public String wxcheck(@RequestParam String signature, @RequestParam String timestamp
		, @RequestParam String nonce, @RequestParam String echostr) {

		/* 1. 开始校验 */
		/* 1.1 将token、timestamp、nonce三个参数进行字典序排序 */
		List<String> tmpArr = new ArrayList<>();
		tmpArr.add(timestamp);
		tmpArr.add(nonce);
		tmpArr.add(token);

		System.out.println();
		System.out.println("参数排序前！");
		for(String tempStr : tmpArr){
			System.out.println(tempStr);
		}

		Collections.sort(tmpArr);

		System.out.println();
		System.out.println("参数排序后！");
		System.out.println();
		for(String tempStr : tmpArr){
			System.out.println(tempStr);
		}

		/* 1.2 将三个参数字符串拼接成一个字符串进行sha1加密 */
		StringBuffer sb = new StringBuffer();
		Iterator<String> tmpIter = tmpArr.iterator();
		while (tmpIter.hasNext()){
			sb.append(String.valueOf(tmpIter.next()));
		}
		String oringinEncry = sb.toString();
		String afterEncry = DigestUtils.sha1Hex(oringinEncry);

		System.out.println();
		System.out.println("校验后！");
		System.out.println("timestamp ：" + timestamp + "\n"
				+ "nonce ：" + nonce + "\n"
				+ "token ：" + token + "\n"
				+ "oringinEncry ：" + oringinEncry + "\n"
				+ "afterEncry ：" + afterEncry + "\n"
				+ "signature ：" + signature + "\n"
				+ "echostr ：" + echostr + "\n"

		);

		/* 1.3 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信，
		 * 如果校验成功则返回echostr，成为者成功，否则失败 */
		if(afterEncry.equals(signature)){
			return echostr;
		}
		return null;
	}

	
}
